<template>
    <!-- 导航栏 -->
<!--    <div  class="header-box">-->

<!--    </div>-->
    <!--无数据时的显示策略-->
    <div v-if="state.isNoData" class="autobox-container-ar" style="display: flex; align-items: center; justify-content: center" >
        <img src="@/assets/imge/暂无数据.jpg" alt="暂无数据" style="width: 280px; height: 280px">
    </div>
    <div v-else class="autobox-container-ar">
        <!--博客列表开始-->
        <div class="blog-list">
            <!-- 卡片 -->
            <div class="blog-item" v-for="item in state.projectList" :key="item.projectId">
                <!-- 内容主体区域 -->
                <div class="blog-main-content">
                    <router-link :to="`/projects/${item.projectId}`">
                        <div style="display: flex; align-items: center; justify-content: space-between">
                            <!-- 标题 + 内容（左） -->
                            <div style="width: 860px" >
                                <div style="display:flex;">
                                    <el-avatar :src="item.user?.profile_photo_path" shape="circle" :size="30" @error="errorHandler">
                                        <img
                                                src="https://cube.elemecdn.com/e/fd/0fc7d20532fdaf769a25683617711png.png"
                                                alt="加载错误"/> <!--图片加载失败的回退行为-->
                                    </el-avatar>
                                    <strong class="blog-title">{{item.user?.username}} / {{item?.projectName}}</strong>
                                </div>
                                <div class="blog-desc">{{ item.description }}</div><!-- DOMPurify 库去除HTML标签 -->
                            </div>
                            <span class="icon-item"><img src="@/assets/icon_svg/_收藏.svg" alt="icon" style="width: 20px; height: 20px; margin-right: 5px"> {{ item.collections }}</span>
                        </div>
                    </router-link>
                    <!-- 文章信息区域（预留）：置于内容底部靠左-->
                    <div class="user-info-area">
                        <!--分类标签区域-->
                        <div style="display: flex">
                            <span style="display: flex"><img src="@/assets/icon_svg/浏览量.svg" alt="icon" style="width: 20px; height: 20px; margin-right: 5px">{{ item.views }}&nbsp;&nbsp;&nbsp;&nbsp;</span>
                            <span v-if="item.category"><el-tag type="info">{{ item.category?.categoryName }}</el-tag>&nbsp;&nbsp;&nbsp;&nbsp;|&nbsp;&nbsp;&nbsp;&nbsp;</span>
                            <span v-else><el-tag type="info">其他</el-tag>&nbsp;&nbsp;&nbsp;&nbsp;|&nbsp;&nbsp;&nbsp;&nbsp;</span>
                            <span v-if="item.tags" class="tag-list"><el-tag v-for="tag in item.tags.split(',')" :key="tag" type="success">{{ tag }}</el-tag></span>
                            <span v-else><el-tag type="success">其他</el-tag></span>
                            <span class="publish-time">&nbsp;&nbsp;&nbsp;&nbsp;|&nbsp;&nbsp;&nbsp;&nbsp;{{ formatTimeAgo(item.createdAt) }}</span>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <!--博客列表结束-->
        <!-- 加载更多提示 -->
        <div ref="loadMoreTip" v-if="!state.isLoading && state.hasMore" class="load-more-tip">滑动加载更多</div>
        <div v-if="state.isLoading" class="load-more-tip">加载中...</div>
    </div>
  <!-- 文章内容区 auto 结束-->
</template>

<script setup>
//获取本地存储中的用户信息
import {reactive, ref, onMounted, onUnmounted} from "vue";
import {ElMessage} from "element-plus";
import request from "@/utils/request.js";

let user;
const loginUser = localStorage.getItem('code_user');
if (loginUser) {
    // 将拿到的Json数据转化为JavaScript对象
    user = JSON.parse(loginUser);
}

// 初始化加载
onMounted(() => {
    loadBlogs(state.nextPageNum);
    window.addEventListener('scroll', handleScroll);
});

// 移除滚动监听
onUnmounted(() => {
    window.removeEventListener('scroll', handleScroll);
});


// 缓存所有内容
const allContent = ref([]);
const state = reactive({
    nextPageNum: 1, // 下一次加载的页码
    pageSize: 7, // 固定每页加载数量
    total: 0,
    projectList: [],  //
    heatContent: [],   // 热度内容列表
    isLoading: false, // 加载状态
    hasMore: true, // 是否还有更多数据
    isNoData: false, // 是否有数据
});
const errorHandler = () => true //图片加载失败的回退行为
// 滚动事件处理
const loadMoreTip = ref(null);

const handleScroll = () => {
    if (state.isLoading || !state.hasMore) return;
    const scrollTop = document.documentElement.scrollTop || document.body.scrollTop;
    const clientHeight = document.documentElement.clientHeight;
    const scrollHeight = document.documentElement.scrollHeight;

    // 距离底部100px时触发加载
    if (scrollTop + clientHeight >= scrollHeight - 100) {
        loadBlogs(state.nextPageNum);
    }
};

// 加载博客列表（支持无限滚动）
const loadBlogs = (pageNum) => {
    state.isLoading = true;
    request.get('/api/projects/selectProjectsPageByUser', {
        params: {
            pageNum,
            pageSize: state.pageSize,
            userId: user.user_id,
        }
    }).then(res => {
        if (res.code === '200') {
            const newList = res.data.list;
            state.isNoData = res.data.list.length === 0
            // 自动分页加载
            state.projectList = [...state.projectList, ...newList]; // 合并新数据
            allContent.value = [...allContent.value, ...newList]; // 缓存新数据
            state.total = res.data.total;
            state.nextPageNum = pageNum + 1; // 准备下一页
            state.hasMore = newList.length === state.pageSize; // 判断是否还有更多数据
        } else {
            ElMessage.error(res.msg);
        }
    }).catch(error => {
        console.error(error);
    }).finally(() => {
        state.isLoading = false;
    });
};

// 工具函数：格式化时间
const formatTimeAgo = (time) => {
    const now = new Date();
    const created = new Date(time);
    const diffMs = now - created;
    const diffSec = Math.floor(diffMs / 1000);
    const diffMin = Math.floor(diffSec / 60);
    const diffHour = Math.floor(diffMin / 60);
    const diffDay = Math.floor(diffHour / 24);

    if (diffSec < 60) {
        return `${diffSec}秒前`;
    } else if (diffMin < 60) {
        return `${diffMin}分钟前`;
    } else if (diffHour < 24) {
        return `${diffHour}小时前`;
    } else if (diffDay === 1) {
        return '昨天';
    } else if (diffDay < 7) {
        return `${diffDay}天前`;
    } else if (diffDay < 30) {
        return `${Math.floor(diffDay / 7)}周前`;
    } else {
        return `${Math.floor(diffDay / 30)}个月前`;
    }
};
</script>

<style scoped>
/* 导航菜单容器样式 */
.header-box {
    border-bottom: 1px solid #e8e8e8;
    margin-bottom: 20px;
}
/*中间内容区域容器：*/
.autobox-container-ar {
    position: absolute;
    /*right: 267px;*/
    width: 970px;
    box-sizing: border-box;
    background-color: #fffefb;
    min-height: 80vh;
}
/*卡片样式*/
.blog-item {
    display: flex;
    flex-direction: row;
    align-items: flex-start;
    gap: 22px;
    padding: 15px 30px;
    border-bottom: 2px #f5f4f1 solid;
    transition: transform 0.3s, box-shadow 0.3s;
}
.blog-item:hover {
    background-color: #f5f4f1;
    box-shadow: 0 2px 10px rgba(0, 0, 0, 0.10); /* 轻微外阴影 */
}
/* 用户信息区域样式 */
.user-info-area {
    width: 100%;
    display: flex;
    align-items: center;
}

/* 内容主体区域样式 */
.blog-main-content {
    display: flex;
    flex-direction: column;
}

/*标题样式*/
.blog-title {
    font-size: 18px;
    font-weight: 600;
    color: #1a1a1a;
}
/*内容样式*/
.blog-desc {
    font-size: 14px;
    line-height: 1.6;
    color: #4f4f4f;
    overflow: hidden;
    text-overflow: ellipsis;
    display: -webkit-box;
    -webkit-box-orient: vertical;
    -webkit-line-clamp: 3; /* 限制3行 */
    padding: 15px 0;
}
.icon-item {
    display: flex;
    align-items: center;
    gap: 5px;
    transition: all 0.2s;
}
.liked img {
    filter: brightness(0.8) hue-rotate(180deg); /* 点赞后图标变色 */
}


/* 加载提示样式 */
.load-more-tip {
    width: 100%;
    height: 50px;
    line-height: 50px;
    text-align: center;
    color: #666;
    font-size: 0.95em;
    padding: 16px;
    border-top: 1px solid #f0f0f0;
}
.blog-title {
    font-size: 18px;
    font-weight: 600;
    color: #1f2937;
    margin-bottom: 8px;
    display: block;
    margin-left: 10px;
}
</style>